<template>
  <div class="map-block">
    <!-- 编辑模式 -->
    <div v-if="!previewMode" class="map-editor">
      <el-form label-position="top" size="small">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="地点名称">
              <el-input
                v-model="localContent.title"
                placeholder="请输入地点名称"
                @input="handleUpdate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址">
              <el-input
                v-model="localContent.address"
                placeholder="请输入详细地址"
                @input="handleUpdate"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="纬度">
              <el-input-number
                v-model="localContent.latitude"
                :precision="6"
                :step="0.000001"
                @change="handleUpdate"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="经度">
              <el-input-number
                v-model="localContent.longitude"
                :precision="6"
                :step="0.000001"
                @change="handleUpdate"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="缩放级别">
              <el-slider
                v-model="localContent.zoom"
                :min="1"
                :max="20"
                @change="handleUpdate"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述信息">
          <el-input
            v-model="localContent.description"
            type="textarea"
            :rows="2"
            placeholder="请输入地点描述（可选）"
            @input="handleUpdate"
          />
        </el-form-item>
        
        <!-- 地图样式设置 -->
        <el-divider content-position="left">地图样式</el-divider>
        
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="地图高度">
              <el-input-number
                v-model="localContent.height"
                :min="200"
                :max="600"
                @change="handleUpdate"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地图主题">
              <el-select
                v-model="localContent.theme"
                @change="handleUpdate"
              >
                <el-option label="标准" value="standard" />
                <el-option label="卫星" value="satellite" />
                <el-option label="混合" value="hybrid" />
                <el-option label="地形" value="terrain" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标记样式">
              <el-select
                v-model="localContent.markerStyle"
                @change="handleUpdate"
              >
                <el-option label="默认" value="default" />
                <el-option label="自定义" value="custom" />
                <el-option label="动画" value="animated" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="显示控件">
              <el-switch
                v-model="localContent.showControls"
                @change="handleUpdate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="可拖拽">
              <el-switch
                v-model="localContent.draggable"
                @change="handleUpdate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="显示信息窗">
              <el-switch
                v-model="localContent.showInfoWindow"
                @change="handleUpdate"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button @click="getCurrentLocation" size="small">
            <el-icon><Location /></el-icon>
            获取当前位置
          </el-button>
          <el-button @click="searchLocation" size="small">
            <el-icon><Search /></el-icon>
            搜索地点
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 预览模式 -->
    <div v-else class="map-preview">
      <div 
        class="map-container"
        :class="{
          'animated-marker': localContent.markerStyle === 'animated',
          'custom-theme': localContent.theme !== 'standard'
        }"
        :style="{ height: `${localContent.height}px` }"
      >
        <!-- 地图头部信息 -->
        <div v-if="localContent.title || localContent.address" class="map-header">
          <h3 v-if="localContent.title" class="map-title">
            <el-icon><Location /></el-icon>
            {{ localContent.title }}
          </h3>
          <p v-if="localContent.address" class="map-address">{{ localContent.address }}</p>
        </div>
        
        <!-- 模拟地图区域 -->
        <div class="map-canvas" ref="mapCanvas">
          <!-- 地图背景 -->
          <div class="map-background" :class="`theme-${localContent.theme}`">
            <!-- 网格线 -->
            <div class="map-grid"></div>
            
            <!-- 地图标记 -->
            <div 
              class="map-marker"
              :class="{
                'marker-animated': localContent.markerStyle === 'animated',
                'marker-custom': localContent.markerStyle === 'custom'
              }"
              :style="markerPosition"
            >
              <div class="marker-icon">
                <el-icon><Location /></el-icon>
              </div>
              <div class="marker-pulse" v-if="localContent.markerStyle === 'animated'"></div>
              
              <!-- 信息窗口 -->
              <div v-if="localContent.showInfoWindow" class="info-window">
                <div class="info-content">
                  <h4 v-if="localContent.title">{{ localContent.title }}</h4>
                  <p v-if="localContent.description">{{ localContent.description }}</p>
                  <p v-if="localContent.address" class="info-address">{{ localContent.address }}</p>
                </div>
                <div class="info-arrow"></div>
              </div>
            </div>
            
            <!-- 地图控件 -->
            <div v-if="localContent.showControls" class="map-controls">
              <div class="zoom-controls">
                <button class="zoom-btn">+</button>
                <button class="zoom-btn">-</button>
              </div>
              <div class="map-type-control">
                <select>
                  <option>地图</option>
                  <option>卫星</option>
                </select>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 地图底部信息 -->
        <div v-if="localContent.description" class="map-footer">
          <p>{{ localContent.description }}</p>
        </div>
      </div>
    </div>
    
    <!-- 位置搜索对话框 -->
    <el-dialog v-model="searchDialogVisible" title="搜索地点" width="500px">
      <el-input
        v-model="searchQuery"
        placeholder="请输入地点名称或地址"
        @keyup.enter="performSearch"
      >
        <template #append>
          <el-button @click="performSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      
      <div v-if="searchResults.length > 0" class="search-results">
        <div 
          v-for="(result, index) in searchResults"
          :key="index"
          class="search-result-item"
          @click="selectSearchResult(result)"
        >
          <h4>{{ result.name }}</h4>
          <p>{{ result.address }}</p>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="searchDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Location, Search } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  block: {
    type: Object,
    required: true
  },
  previewMode: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update'])

// 本地内容状态
const localContent = ref({
  title: '台湾大学',
  address: '台北市大安区罗斯福路四段1号',
  latitude: 25.0330,
  longitude: 121.5654,
  zoom: 15,
  description: '国立台湾大学，简称台大，是台湾的顶尖学府。',
  height: 300,
  theme: 'standard',
  markerStyle: 'animated',
  showControls: true,
  draggable: false,
  showInfoWindow: true,
  ...props.block.content
})

// 搜索相关状态
const searchDialogVisible = ref(false)
const searchQuery = ref('')
const searchResults = ref([])

// 地图画布引用
const mapCanvas = ref(null)

// 计算标记位置
const markerPosition = computed(() => {
  // 基于缩放级别和坐标计算标记位置
  const zoom = localContent.value.zoom
  const centerX = 50 // 地图中心X坐标百分比
  const centerY = 50 // 地图中心Y坐标百分比
  
  return {
    left: `${centerX}%`,
    top: `${centerY}%`,
    transform: 'translate(-50%, -100%)'
  }
})

/**
 * 处理内容更新
 */
const handleUpdate = () => {
  emit('update', {
    content: { ...localContent.value }
  })
}

/**
 * 获取当前位置
 */
const getCurrentLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        localContent.value.latitude = position.coords.latitude
        localContent.value.longitude = position.coords.longitude
        localContent.value.title = '当前位置'
        localContent.value.address = '通过GPS获取的位置'
        handleUpdate()
        ElMessage.success('位置获取成功')
      },
      (error) => {
        ElMessage.error('无法获取当前位置：' + error.message)
      }
    )
  } else {
    ElMessage.error('浏览器不支持地理位置服务')
  }
}

/**
 * 搜索地点
 */
const searchLocation = () => {
  searchDialogVisible.value = true
  searchQuery.value = ''
  searchResults.value = []
}

/**
 * 执行搜索
 */
const performSearch = () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  // 模拟搜索结果
  const mockResults = [
    {
      name: '台湾大学',
      address: '台北市大安区罗斯福路四段1号',
      latitude: 25.0330,
      longitude: 121.5654
    },
    {
      name: '台北101',
      address: '台北市信义区信义路五段7号',
      latitude: 25.0340,
      longitude: 121.5645
    },
    {
      name: '中正纪念堂',
      address: '台北市中正区中山南路21号',
      latitude: 25.0320,
      longitude: 121.5200
    }
  ].filter(item => 
    item.name.includes(searchQuery.value) || 
    item.address.includes(searchQuery.value)
  )
  
  searchResults.value = mockResults
  
  if (mockResults.length === 0) {
    ElMessage.info('未找到相关地点')
  }
}

/**
 * 选择搜索结果
 * @param {object} result - 搜索结果
 */
const selectSearchResult = (result) => {
  localContent.value.title = result.name
  localContent.value.address = result.address
  localContent.value.latitude = result.latitude
  localContent.value.longitude = result.longitude
  handleUpdate()
  searchDialogVisible.value = false
  ElMessage.success('地点设置成功')
}

// 监听 props 变化
watch(
  () => props.block.content,
  (newContent) => {
    localContent.value = {
      ...localContent.value,
      ...newContent
    }
  },
  { deep: true }
)
</script>

<style scoped>
.map-block {
  width: 100%;
}

.map-editor {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.map-preview {
  width: 100%;
}

.map-container {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background: white;
}

.map-header {
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.map-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.map-address {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.map-canvas {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.map-background {
  width: 100%;
  height: 100%;
  position: relative;
  background: #f0f0f0;
}

.theme-standard {
  background: linear-gradient(45deg, #e8f4f8 25%, transparent 25%), 
              linear-gradient(-45deg, #e8f4f8 25%, transparent 25%), 
              linear-gradient(45deg, transparent 75%, #e8f4f8 75%), 
              linear-gradient(-45deg, transparent 75%, #e8f4f8 75%);
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
}

.theme-satellite {
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
}

.theme-hybrid {
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
}

.theme-terrain {
  background: linear-gradient(135deg, #8fbc8f 0%, #228b22 100%);
}

.map-grid {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    linear-gradient(rgba(0,0,0,0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0,0,0,0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  opacity: 0.3;
}

.map-marker {
  position: absolute;
  z-index: 10;
}

.marker-icon {
  width: 30px;
  height: 30px;
  background: #ff4757;
  border-radius: 50% 50% 50% 0;
  transform: rotate(-45deg);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.marker-icon .el-icon {
  transform: rotate(45deg);
}

.marker-animated .marker-icon {
  animation: bounce 2s infinite;
}

.marker-pulse {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 60px;
  height: 60px;
  background: rgba(255, 71, 87, 0.3);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  animation: pulse 2s infinite;
}

.marker-custom .marker-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  transform: none;
}

.marker-custom .marker-icon .el-icon {
  transform: none;
}

.info-window {
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  margin-bottom: 10px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  min-width: 200px;
  max-width: 300px;
}

.info-content {
  padding: 12px;
}

.info-content h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.info-content p {
  margin: 0 0 4px 0;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.info-address {
  color: #999 !important;
}

.info-arrow {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-top: 8px solid white;
}

.map-controls {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.zoom-controls {
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.zoom-btn {
  width: 30px;
  height: 30px;
  border: none;
  background: white;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: background-color 0.2s;
}

.zoom-btn:hover {
  background: #f0f0f0;
}

.zoom-btn:not(:last-child) {
  border-bottom: 1px solid #e0e0e0;
}

.map-type-control select {
  padding: 6px 8px;
  border: none;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-size: 12px;
}

.map-footer {
  padding: 16px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.map-footer p {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.search-results {
  margin-top: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.search-result-item {
  padding: 12px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.search-result-item:hover {
  background: #f8f9fa;
  border-color: #409eff;
}

.search-result-item h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #333;
}

.search-result-item p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

/* 动画效果 */
@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0) rotate(-45deg);
  }
  40% {
    transform: translateY(-10px) rotate(-45deg);
  }
  60% {
    transform: translateY(-5px) rotate(-45deg);
  }
}

@keyframes pulse {
  0% {
    transform: translate(-50%, -50%) scale(0.8);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(2);
    opacity: 0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-header {
    padding: 12px;
  }
  
  .map-title {
    font-size: 16px;
  }
  
  .map-controls {
    top: 5px;
    right: 5px;
  }
  
  .info-window {
    min-width: 150px;
    max-width: 200px;
  }
}
</style>